package com.example.memorycardgame;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.memorycardgame.model.Card;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CardGameActivity extends AppCompatActivity {
    private GridLayout gridLayout;
    private TextView tvScore, tvHighScore;
    private Button btnRestart;

    // 游戏配置
    private static final int ROWS = 4;
    private static final int COLS = 4;
    private static final int TOTAL_CARDS = ROWS * COLS;
    private static final int MATCH_SCORE = 10;   // 匹配成功得分
    private static final int MISMATCH_PENALTY = 2; // 匹配失败扣分

    // 卡片图片资源（需在drawable目录添加对应图片）
    private int[] cardImageResIds = {
            R.drawable.ic_card1, R.drawable.ic_card2, R.drawable.ic_card3, R.drawable.ic_card4,
            R.drawable.ic_card5, R.drawable.ic_card6, R.drawable.ic_card7, R.drawable.ic_card8,
            R.drawable.ic_card1, R.drawable.ic_card2, R.drawable.ic_card3, R.drawable.ic_card4,
            R.drawable.ic_card5, R.drawable.ic_card6, R.drawable.ic_card7, R.drawable.ic_card8
    };

    private List<Card> cardList; // 卡片模型列表
    private int currentScore;    // 当前得分
    private int gameHighScore;  // 本局最高分

    // 翻牌状态控制
    private Card firstFlippedCard;
    private Card secondFlippedCard;
    private boolean isProcessing; // 是否正在处理匹配（防止快速点击）

    private Handler handler = new Handler(); // 用于延迟翻牌

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_game);

        // 初始化控件
        initViews();
        // 初始化游戏数据
        initGameData();
        // 创建卡片界面
        createCardViews();
        // 绑定事件
        bindEvents();
    }

    private void initViews() {
        gridLayout = findViewById(R.id.grid_layout);
        tvScore = findViewById(R.id.tv_score);
        tvHighScore = findViewById(R.id.tv_high_score);
        btnRestart = findViewById(R.id.btn_restart);

        // 获取主界面传递的当前最高分
        int currentHighScore = getIntent().getIntExtra("currentHighScore", 0);
        gameHighScore = currentHighScore;
        tvHighScore.setText("最高分：" + gameHighScore);
    }

    private void initGameData() {
        currentScore = 0;
        isProcessing = false;
        firstFlippedCard = null;
        secondFlippedCard = null;

        // 初始化卡片模型列表
        cardList = new ArrayList<>();
        for (int i = 0; i < TOTAL_CARDS; i++) {
            Card card = new Card(cardImageResIds[i], i);
            cardList.add(card);
        }

        // 打乱卡片顺序
        Collections.shuffle(cardList);
    }

    // 创建卡片视图（View）并添加到网格
    private void createCardViews() {
        gridLayout.removeAllViews(); // 清空之前的卡片

        // 设置卡片宽高（自适应屏幕）
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        int cardSize = (screenWidth - (COLS + 1) * 30) / COLS; // 减去padding和间距

        for (int i = 0; i < TOTAL_CARDS; i++) {
            Card card = cardList.get(i);
            ImageView cardView = new ImageView(this);

            // 设置卡片样式
            cardView.setLayoutParams(new GridLayout.LayoutParams(
                    GridLayout.spec(i / COLS),
                    GridLayout.spec(i % COLS)
            ));
            cardView.setAdjustViewBounds(true);
            cardView.setMaxWidth(cardSize);
            cardView.setMaxHeight(cardSize);
            cardView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            cardView.setPadding(5, 5, 5, 5);

            // 初始显示卡片背面
            cardView.setImageResource(R.drawable.ic_card_back);
            cardView.setTag(i); // 存储卡片位置索引

            // 卡片点击事件（控制器核心：接收用户交互）
            cardView.setOnClickListener(v -> handleCardClick((int) v.getTag()));

            gridLayout.addView(cardView);
        }

        // 更新分数显示
        tvScore.setText("当前得分：" + currentScore);
    }

    private void bindEvents() {
        // 重新开始游戏
        btnRestart.setOnClickListener(v -> restartGame());
    }

    // 处理卡片点击（控制器核心：处理模型并同步界面）
    private void handleCardClick(int position) {
        // 防止：正在处理中、点击已匹配的卡片、点击已翻转的第一张卡片
        if (isProcessing ||
                cardList.get(position).isMatched() ||
                (firstFlippedCard != null && firstFlippedCard.getPosition() == position)) {
            return;
        }

        Card clickedCard = cardList.get(position);
        ImageView clickedView = (ImageView) gridLayout.getChildAt(position);

        // 如果是第一张未翻转的卡片
        if (firstFlippedCard == null) {
            firstFlippedCard = clickedCard;
            firstFlippedCard.flip(); // 模型：翻转卡片
            clickedView.setImageResource(firstFlippedCard.getImageResId()); // 界面：同步显示正面
        }
        // 如果是第二张卡片
        else if (secondFlippedCard == null) {
            secondFlippedCard = clickedCard;
            secondFlippedCard.flip(); // 模型：翻转卡片
            clickedView.setImageResource(secondFlippedCard.getImageResId()); // 界面：同步显示正面

            // 检查是否匹配
            checkCardMatch();
        }
    }

    // 检查两张卡片是否匹配（控制器核心：处理模型逻辑）
    private void checkCardMatch() {
        isProcessing = true;

        if (firstFlippedCard.getImageResId() == secondFlippedCard.getImageResId()) {
            // 匹配成功
            handleMatchSuccess();
        } else {
            // 匹配失败
            handleMatchFailure();
        }
    }

    // 匹配成功处理
    private void handleMatchSuccess() {
        currentScore += MATCH_SCORE;
        updateScoreDisplay();

        // 标记卡片为已匹配
        firstFlippedCard.setMatched(true);
        secondFlippedCard.setMatched(true);

        // 重置翻牌状态
        resetFlippedCards();
        isProcessing = false;

        // 检查游戏是否结束
        if (isGameOver()) {
            handler.postDelayed(() -> {
                Toast.makeText(this, "游戏结束！最终得分：" + currentScore, Toast.LENGTH_LONG).show();
                // 更新最高分
                if (currentScore > gameHighScore) {
                    gameHighScore = currentScore;
                    tvHighScore.setText("最高分：" + gameHighScore);
                    // 返回新的最高分给主界面
                    Intent resultIntent = new Intent();
                    resultIntent.putExtra("highScore", gameHighScore);
                    setResult(RESULT_OK, resultIntent);
                }
            }, 500);
        }
    }

    // 匹配失败处理
    private void handleMatchFailure() {
        currentScore = Math.max(0, currentScore - MISMATCH_PENALTY); // 分数不低于0
        updateScoreDisplay();

        // 延迟1秒后翻回背面
        handler.postDelayed(() -> {
            // 模型：翻回背面
            firstFlippedCard.flip();
            secondFlippedCard.flip();

            // 界面：同步显示背面
            ImageView firstView = (ImageView) gridLayout.getChildAt(firstFlippedCard.getPosition());
            ImageView secondView = (ImageView) gridLayout.getChildAt(secondFlippedCard.getPosition());
            firstView.setImageResource(R.drawable.ic_card_back);
            secondView.setImageResource(R.drawable.ic_card_back);

            // 重置翻牌状态
            resetFlippedCards();
            isProcessing = false;
        }, 1000);
    }

    // 重置翻牌状态
    private void resetFlippedCards() {
        firstFlippedCard = null;
        secondFlippedCard = null;
    }

    // 更新分数显示
    private void updateScoreDisplay() {
        tvScore.setText("当前得分：" + currentScore);
    }

    // 检查游戏是否结束（所有卡片都已匹配）
    private boolean isGameOver() {
        for (Card card : cardList) {
            if (!card.isMatched()) {
                return false;
            }
        }
        return true;
    }

    // 重新开始游戏
    private void restartGame() {
        initGameData();
        createCardViews();
        Toast.makeText(this, "游戏重新开始！", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null); // 移除所有延迟任务
    }
}